//验证用户登录中间件（token）
module.exports = options => {
	const jwt = require('jsonwebtoken')
	const assert = require('http-assert')
	const AdminUser = require('../models/AdminUser')

	return async (req, res, next) => {
		//1.获取前端传过来的token,转为字符串，通过空格截取将Bearer与token分为两节，pop取后一项
		const token = String(req.headers.authorization || '').split(' ').pop()
		assert(token, 401, '请先登录')
		//2.解析token中的数据
		const { id } = jwt.verify(token, req.app.get('secret'))
		assert(token, 401, '请先登录')
		//3.根据解析出来的id去数据库中查询相关的信息
		req.user = await AdminUser.findById(id)
		assert(req.user, 401, '请先登录')
		await next()
	}
} 